import React, { useMemo, useState, useEffect, useCallback } from 'react';
import { Outlet, useNavigate } from "react-router";
import type { Route } from "./+types/home";
// antd 
import {
  OpenAIOutlined,
  MenuOutlined,
  HistoryOutlined,
  SettingOutlined,
  FullscreenOutlined,
  EnterOutlined,
  DatabaseOutlined,
  UsbFilled,
  LogoutOutlined,
  MenuUnfoldOutlined,
  MenuFoldOutlined,
  UserSwitchOutlined
} from '@ant-design/icons';
import type { MenuProps, TabsProps, DropdownProps } from 'antd';
import {
  Layout,
  Menu,
  theme,
  Dropdown,
  Avatar,
  Typography,
  Space,
  Button,
  Tabs,
  message
} from 'antd';

import ProtectedRoute from '../protectedRoute'
import { useAuth } from '../authProvider'
import type { IAuthUser } from '../types/system'
import { imgBaseURL } from '../api/baseURL'
import http from '../api/http'

const { Text } = Typography;

export function meta({ }: Route.MetaArgs) {
  return [
    { title: "欢迎来到React Router" },
    { name: "description", content: "Welcome to React Router!" },
  ];
}

// 定义菜单项的接口类型
interface MenuItem {
  menuId: number;
  menuName: string;
  url: string;
  parentId: number;
  icon: string;
  lastTime: string;
  children?: MenuItem[] | null;
}

// 图标映射表
const IconMap = {
  Operation: OpenAIOutlined,
  Menu: MenuOutlined,
  Histogram: HistoryOutlined,
  Setting: SettingOutlined,
  FullScreen: FullscreenOutlined,
  Odometer: EnterOutlined,
  DataAnalysis: DatabaseOutlined,
  Open: OpenAIOutlined,
  UsbFilled: UsbFilled
};

// 将扁平的菜单数据转换为树形结构
const buildMenuTree = (items: MenuItem[], parentId = 0): MenuItem[] => {
  return items
    .filter(item => item.parentId === parentId)
    .map(item => {
      const children = buildMenuTree(items, item.menuId);
      return {
        ...item,
        children: children.length > 0 ? children : null
      };
    });
};

// 将树形菜单转换为Ant Design Menu组件需要的格式
const convertToMenuItems = (menuTree: MenuItem[]): MenuProps['items'] => {
  return menuTree.map(item => {
    // 获取图标组件
    const IconComponent = item.icon && IconMap[item.icon as keyof typeof IconMap];

    const menuItem: any = {
      key: item.menuId.toString(),
      label: item.menuName,
      icon: IconComponent ? React.createElement(IconComponent) : null
    };

    // 如果有子菜单，递归处理
    if (item.children && item.children.length > 0) {
      menuItem.children = convertToMenuItems(item.children);
    }

    return menuItem;
  });
};

// antd layout
const { Header, Content, Sider } = Layout;
const SIDER_WIDTH = 200; // 侧边栏宽度
const COLLAPSED_SIDER_WIDTH = 80; // 折叠状态的侧边栏宽度

// 定义Tab项接口
interface TabItem {
  key: string; // 使用menuId作为key
  title: string; // 菜单名称
  url: string; // 对应的路由
  closable?: boolean; // 是否可关闭
}

// 模拟用户数据
const mockUsers: IAuthUser[] = [
  {
    userName: '张三',
    imgPath: 'https://picsum.photos/id/1/200',
    roleName: '管理员',
    token: ''
  },
  {
    userName: '李四',
    imgPath: 'https://picsum.photos/id/2/200',
    roleName: '普通用户',
    token: ''
  },
  {
    userName: '王五',
    imgPath: 'https://picsum.photos/id/3/200',
    roleName: '访客',
    token: ''
  }
];

export default function Home() {
  const {
    token: { colorBgContainer, borderRadiusLG },
  } = theme.useToken();

  const navigate = useNavigate()
  const { logout, user } = useAuth() //退出登录
  const [collapsed, setCollapsed] = useState(false);
  const [selectedKeys, setSelectedKeys] = useState<string[]>([]);
  const [openKeys, setOpenKeys] = useState<string[]>([]);
  const [currentUser, setCurrentUser] = useState<IAuthUser>(user ? user : { userName: '游客', roleName: '访客', imgPath: '', token: '' });
  const [menuData, setMenuData] = useState<Array<MenuItem>>([])

  // 获取菜单 - 使用useCallback确保引用稳定
  const fetchMenus = useCallback(async () => {
    try {
      const response = await http.get<Array<MenuItem>>('Menus');
      setMenuData(response.data)
    } catch (error) {
      console.error('获取用户数据失败:', error);
      message.error('获取用户数据失败，请稍后重试');
    }
  }, []);

  // 修复：添加fetchMenus到依赖数组
  useEffect(() => {
    // 更新登录用户信息
    const storedUser = sessionStorage.getItem('user');
    if (storedUser) {
      setCurrentUser(JSON.parse(storedUser));
    }
    // 获取菜单
    fetchMenus();
  }, [fetchMenus]); // 现在依赖项完整了

  // Tab相关状态
  const [tabs, setTabs] = useState<TabItem[]>([
    { key: '0', title: '首页', url: '/', closable: false }
  ]);
  const [activeTabKey, setActiveTabKey] = useState<string>('0');

  // 用户菜单点击事件处理
  const handleUserMenuClick: MenuProps['onClick'] = ({ key }) => {
    switch (key) {
      case 'switch':
        // 切换到下一个用户
        const currentIndex = mockUsers.findIndex(u => u.userName === currentUser.userName);
        const nextIndex = (currentIndex + 1) % mockUsers.length;
        const newUser = mockUsers[nextIndex];
        setCurrentUser(newUser);
        sessionStorage.setItem('user', JSON.stringify(newUser)); // 保存到sessionStorage
        message.success(`已切换到用户: ${newUser.userName}`);
        break;
      case 'logout':
        // 退出登录逻辑
        logout();
        message.success('已退出登录');
        navigate('/login');
        break;
      case 'setting':
        // 账户设置逻辑
        message.info('前往账户设置');
        // navigate('/account/setting');
        break;
      default:
        break;
    }
  };

  // 用户下拉菜单配置
  const userMenuItems: MenuProps['items'] = [
    {
      key: 'setting',
      icon: <SettingOutlined />,
      label: '账户设置',
    },
    {
      key: 'switch',
      icon: <UserSwitchOutlined />,
      label: '切换账户',
    },
    {
      type: 'divider',
    },
    {
      key: 'logout',
      icon: <LogoutOutlined />,
      label: '退出登录',
      danger: true,
    },
  ];

  // 用户下拉菜单属性
  const dropdownProps: DropdownProps = {
    menu: {
      items: userMenuItems,
      onClick: handleUserMenuClick
    },
    placement: 'bottomRight',
    arrow: true,
  };

  // 使用useMemo缓存菜单树构建结果
  const { menuTree, menuItems } = useMemo(() => {
    if (!menuData || menuData.length === 0) {
      return { menuTree: [], menuItems: [] };
    }
    const tree = buildMenuTree(menuData);
    return {
      menuTree: tree,
      menuItems: convertToMenuItems(tree)
    };
  }, [menuData]);  // 当menuData变化时重新计算

  // 处理菜单点击 - 添加或切换Tab
  const onSelect: MenuProps['onSelect'] = (info) => {
    // 根据key(menuId)查找对应的菜单项
    const selectedItem = menuData?.find(item => item.menuId.toString() === info.key);

    if (selectedItem && selectedItem.url) {
      // 更新选中的菜单
      setSelectedKeys([info.key]);

      // 检查该Tab是否已存在
      const existingTabIndex = tabs.findIndex(tab => tab.key === info.key);

      if (existingTabIndex > -1) {
        // 切换到已存在的Tab
        setActiveTabKey(info.key);
      } else {
        // 添加新Tab
        const newTab: TabItem = {
          key: info.key,
          title: selectedItem.menuName,
          url: selectedItem.url,
          closable: true
        };

        setTabs(prevTabs => [...prevTabs, newTab]);
        setActiveTabKey(info.key);
      }

      navigate(selectedItem.url);
    }
  };

  // 处理Tab关闭
  const handleTabClose = (key: React.MouseEvent | React.KeyboardEvent | string) => {
    // 统一处理key为字符串类型
    const tabKey = typeof key === 'string' ? key : key.currentTarget.id;
    
    // 不能关闭首页
    if (tabKey === '0') return;

    // 使用函数式更新确保获取最新的tabs状态
    setTabs(prevTabs => {
      const newTabs = prevTabs.filter(tab => tab.key !== tabKey);
      
      // 如果关闭的是当前激活的Tab，需要设置新的激活Tab
      if (tabKey === activeTabKey) {
        // 找到关闭Tab的索引
        const closedIndex = prevTabs.findIndex(tab => tab.key === tabKey);
        // 确定新的激活Tab
        const newActiveKey = newTabs[closedIndex]?.key || newTabs[closedIndex - 1]?.key || '0';
        setActiveTabKey(newActiveKey);
        
        // 同步更新菜单选中状态和路由
        const activeTab = newTabs.find(tab => tab.key === newActiveKey);
        if (activeTab && activeTab.key !== '0') {
          setSelectedKeys([activeTab.key]);
          const url = menuData?.find(v => v.menuId === parseInt(activeTab.key))?.url;
          navigate(url || '/');
        } else {
          setSelectedKeys([]);
          navigate('/');
        }
      }
      
      return newTabs;
    });
  };

  // 处理Tab 手动点击 切换
  const handleTabChange = (key: string) => {
    setActiveTabKey(key);
    // 同步更新菜单选中状态（首页不需要选中菜单）
    if (key !== '0') {
      setSelectedKeys([key]);
    } else {
      setSelectedKeys([]);
    }

    // 点击跳转
    const url = menuData?.find(v => v.menuId === parseInt(key))?.url;
    navigate(url || '/');
  };

  // 处理侧边栏折叠/展开
  const toggleCollapsed = () => {
    setCollapsed(!collapsed);
  };

  // 生成Tabs组件的items
  const generateTabItems = (): TabsProps['items'] => {
    return tabs.map(tab => ({
      key: tab.key,
      label: tab.title,
      closable: tab.closable
    }));
  };

  return (
    <ProtectedRoute>
      <Layout style={{ height: '100vh' }}>
        <Header style={{
          display: 'flex',
          alignItems: 'center',
          padding: '0 16px',
          boxShadow: '0 2px 8px rgba(0, 0, 0, 0.06)',
          zIndex: 1
        }}>
          {/* 侧边栏折叠/展开按钮 */}
          <Button
            type="text"
            icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
            onClick={toggleCollapsed}
            style={{
              fontSize: '16px',
              width: 64,
              height: 64,
              color: 'white',
            }}
          />

          {/* Logo区域 */}
          <div style={{
            width: collapsed ? COLLAPSED_SIDER_WIDTH : SIDER_WIDTH,
            padding: '0 16px',
            display: 'flex',
            alignItems: 'center',
            transition: 'width 0.2s'
          }}>
            {!collapsed ? (
              <div style={{ fontSize: '1.2rem', fontWeight: 'bold', color: 'white' }}>
                管理系统
              </div>
            ) : (
              <div style={{ fontSize: '1.2rem', fontWeight: 'bold', color: 'white' }}>
                管
              </div>
            )}
          </div>

          {/* 中间区域占位 */}
          <div style={{ flex: 1 }}></div>

          {/* 用户信息和下拉菜单 */}
          <Dropdown {...dropdownProps}>
            <div style={{
              display: 'flex',
              alignItems: 'center',
              color: 'white',
              cursor: 'pointer',
              padding: '0 16px',
              minWidth: 120
            }}>
              <Avatar
                src={imgBaseURL + currentUser.imgPath}
                alt={currentUser.userName}
                style={{
                  marginRight: 12,
                  width: 32,
                  height: 32
                }}
              />
              <Space direction="vertical" size={0} style={{ lineHeight: 1.2 }}>
                <Text style={{ color: 'white', margin: 0, fontSize: '14px' }}>
                  {currentUser.userName}
                </Text>
                <Text style={{
                  color: 'rgba(255, 255, 255, 0.8)',
                  fontSize: '12px',
                  margin: 0
                }}>
                  {currentUser.roleName}
                </Text>
              </Space>
            </div>
          </Dropdown>
        </Header>

        <Layout>
          <Sider
            width={collapsed ? COLLAPSED_SIDER_WIDTH : SIDER_WIDTH}
            style={{
              background: colorBgContainer,
              transition: 'width 0.2s',
              boxShadow: '2px 0 8px rgba(0, 0, 0, 0.06)'
            }}
            collapsible
            collapsed={collapsed}
            onCollapse={(value) => setCollapsed(value)}
            trigger={null}
          >
            <Menu
              mode="inline"
              selectedKeys={selectedKeys}
              openKeys={openKeys}
              onOpenChange={setOpenKeys}
              style={{
                height: '100%',
                borderInlineEnd: 0,
                paddingTop: '16px'
              }}
              items={menuItems}
              onSelect={onSelect}
              inlineCollapsed={collapsed}
            />
          </Sider>

          <Layout style={{ padding: '0 24px 24px' }}>
            <Content
              style={{
                padding: 24,
                margin: 0,
                minHeight: 280,
                background: colorBgContainer,
                borderRadius: borderRadiusLG,
                boxShadow: '0 2px 8px rgba(0, 0, 0, 0.06)',
                marginTop: 16
              }}
            >
              {/* Tabs组件展示内容 */}
              <Tabs
                activeKey={activeTabKey}
                onChange={handleTabChange}
                type="editable-card"
                hideAdd
                onEdit={(targetKey, action) => {
                  if (action === 'remove') {
                    handleTabClose(targetKey);
                  }
                }}
                items={generateTabItems()}
                style={{ width: '100%' }}
                tabBarStyle={{ marginBottom: 20 }}
              />
              <Outlet />
            </Content>
          </Layout>
        </Layout>
      </Layout>
    </ProtectedRoute>
  );
}
